<!DOCTYPE html>


<html lang="zh-CN">
  

    <head>
      <meta charset="utf-8" />
        
      <meta name="description" content="Java、MySql、Spring、JVM、虚拟机、数据库、Docker、Redis" />
      
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>深入理解JVM（二）对象创建与对象访问 |  ACEXS个人博客</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/blog-page/favicon.ico" />
       
<link rel="stylesheet" href="/blog-page/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/blog-page/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/blog-page/atom.xml" title="ACEXS个人博客" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-深入理解JVM（二）对象创建与对象访问"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  深入理解JVM（二）对象创建与对象访问
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/blog-page/2021/10/18/44cac75b5e4e.html" class="article-date">
  <time datetime="2021-10-18T09:27:54.000Z" itemprop="datePublished">2021-10-18</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/blog-page/categories/%E8%AF%BB%E4%B9%A6%E6%88%90%E8%AF%97/">读书成诗</a> / <a class="article-category-link" href="/blog-page/categories/%E8%AF%BB%E4%B9%A6%E6%88%90%E8%AF%97/JVM/">JVM</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">1.5k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">5 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h1 id="Java对象创建流程"><a href="#Java对象创建流程" class="headerlink" title="Java对象创建流程"></a>Java对象创建流程</h1><hr>
<h2 id="检查"><a href="#检查" class="headerlink" title="检查"></a>检查</h2><p>检查这个指令的参数能否再常量池中定位到一个类的符号引用，并且检查这个符号引用代表的类是否已被加载、解析和初始化过。如果没有，必须先执行相应的类加载过程。</p>
<h2 id="内存分配"><a href="#内存分配" class="headerlink" title="内存分配"></a>内存分配</h2><h3 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h3><p>对象所需<a href="">内存大小</a>在类加载完成后便可以完全确定，为对象分配空间的任务实际上便等同于把一块确定大小的内存从Java堆中划分出来。</p>
<h3 id="分配方式"><a href="#分配方式" class="headerlink" title="分配方式"></a>分配方式</h3><p><strong>指针碰撞：</strong>假设Java堆中内存是绝对规整的，所有被使用过的内存都被放在一边，空闲的内存被放在另一边，中间放置一个指针作为分界点的指示器，分配内存，就仅仅是把那个指针向空闲空间方向挪动一段与对象大小相等的距离。</p>
<p><strong>空闲列表：</strong>如果Java堆中的内存并不是规整的，已被使用的内存和空闲内存相互交错在一起，虚拟机就必须维护一个列表，记录上哪些内存块是可用的，再分配时候，从列表中找到一块足够大的空间分配给对象实例，并更新列表上的记录。</p>
<p><em><strong>tips：选择哪种分配方式由Java堆是否规整决定，Java堆是否规整由所采用的垃圾收集器是否带有空间压缩整理的能力决定（如：Serial、ParNew等，带有压缩整理过程，采用指针碰撞；CMS这种基于清除算法的收集器，理论上只能采用空闲列表）</strong></em></p>
<h3 id="原子性"><a href="#原子性" class="headerlink" title="原子性"></a>原子性</h3><p>对象创建在虚拟机中是非常频繁的行为，即时仅仅修改一个指针所指向的位置，并发情况下也不是线程安全的，因此虚拟机采用下面两种策略解决问题：</p>
<p><strong>同步处理：</strong>虚拟机采用<a target="_blank" rel="noopener" href="https://blog.csdn.net/ls5718/article/details/52563959">CAS</a>配上失败重试的方式保证更新操作的原子性</p>
<p>**TLAB（Thread Local Allocation Buffer):**每个线程在Java堆中预先分配一小块内存，称为本地线程分配缓冲区，哪个线程要分配内存，就在哪个线程的本地缓冲区中分配，只有本地缓冲区用完，分配新的缓冲区时，才需要同步锁定。</p>
<h2 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h2><p><strong>初始化零值：</strong>内存分配完成后，虚拟机必须将分配到的内存空间（不包括对象头）都初始化为零值，若使用TLAB，这项工作可以提前至TLAB分配时顺便进行。</br></p>
<p><strong>对象头设置：</strong>初始化完成后，要在对象头中设置有关对象的相关设置，如：标记是哪个类的实例，如何找到类的元数据信息、GC分代年龄信息等等。</br></p>
<p><strong>构造函数：</strong>执行构造函数（即Class文件中的<init>()方法），按照程序员意愿进行初始化。</p>
<h1 id="对象内存分布"><a href="#对象内存分布" class="headerlink" title="对象内存分布"></a>对象内存分布</h1><hr>
<h2 id="对象头"><a href="#对象头" class="headerlink" title="对象头"></a>对象头</h2><p><strong><a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36434742/article/details/106854061">Mark Word</a>（对象自身运行时数据）</strong></p>
<ul>
<li>哈希码（HashCode）</li>
<li>GC分代年龄</li>
<li>锁状态标志</li>
<li>线程持有锁</li>
<li>偏向线程ID</li>
<li>偏向时间戳 （等）</li>
</ul>
<p><strong>类型指针（指向类型元数据的指针）</strong></p>
<p>通过这个指针来确定该对象是哪个类型的实例。</p>
<p><strong>数组长度 （非Java数组不存在此信息）</strong></p>
<p>如果对象是Java数组，对象头中必须有一块用于记录数组长度的数据，虚拟机可以通过普通Java对象的元数据信息确定Java对象大小，但是数组长度是不确定的，将无法通过元数据中的信息推断出数组大小。</p>
<h2 id="实例数据"><a href="#实例数据" class="headerlink" title="实例数据"></a>实例数据</h2><p><strong>虚拟机默认分配顺序：</strong> longs/doubles、ints、shorts/chars、bytes/booleans、oops。（相同宽度字段总是被分配到一起存放）。</p>
<p><strong>其他顺序：</strong></p>
<ul>
<li>在满足默认分配顺序前提下，父类中定义的变量会出现在子类之前。</li>
<li>HotSpot虚拟机参数（+XX:CompactFields=true)，子类中较窄的变量允许插入父类变量的空隙中，以此来节省部分空间。（默认为true）</li>
</ul>
<h2 id="对齐填充"><a href="#对齐填充" class="headerlink" title="对齐填充"></a>对齐填充</h2><p><strong>作用：</strong>仅仅起占位符作用，没有特别含义，也不是必然存在的。</p>
<p><strong>原理：</strong>HotSopt虚拟机自动内存管理系统要求对象起始地址必须是8字节的整数倍，也就是任何对象大小都必须是8字节的整数倍。对象头被精心设计成8自己的整数倍，因此如果对象实例数据部分没有对齐的话，需要通过对齐填充来补全。</p>
<h1 id="对象访问定位"><a href="#对象访问定位" class="headerlink" title="对象访问定位"></a>对象访问定位</h1><hr>
<p>《Java虚拟机规范》规定了reference类型是一个指向对象的引用，没有定义这个引用应该通过什么方式去定位、访问到堆中对象的具体位置，所以对象访问方式由虚拟机实现而定。reference数据存储在栈上，通过它操作具体对象。</p>
<h2 id="使用句柄"><a href="#使用句柄" class="headerlink" title="使用句柄"></a>使用句柄</h2><p><strong>原理：</strong>Java堆中将可能划分出一块内存作为句柄池，reference中存储的就是对象的句柄地址，而句柄中包含了对象实例数据与类型数据各自具体地址信息。</p>
<p><strong>示意图：</strong></p>
<img src="/blog-page/2021/10/18/44cac75b5e4e/handler.jpg" class="" width="540" title="This is handler">

<h2 id="直接指针"><a href="#直接指针" class="headerlink" title="直接指针"></a>直接指针</h2><p><strong>原理：</strong>Java堆中对象的内存布局必须考虑如何放置访问类型数据的相关信息，reference中存储的直接就是对象地址，如果访问对象本身，不需要多一次间接访问开销。</p>
<p><strong>示意图：</strong></p>
<img src="/blog-page/2021/10/18/44cac75b5e4e/pointer.jpg" class="" width="540" title="This is pointer">

<h2 id="特征对比"><a href="#特征对比" class="headerlink" title="特征对比"></a>特征对比</h2><table>
<thead>
<tr>
<th>名称</th>
<th>优势</th>
<th>缺点</th>
</tr>
</thead>
<tbody><tr>
<td>直接指针</td>
<td>速度快，节省了以此指针定位的时间开销</td>
<td>对象移动时需要复制对象实例数据，会产生较大的开销</td>
</tr>
<tr>
<td>句柄访问</td>
<td>在对象被移动时，只会改变句柄中的实例数据指针，开销更小（对象实例指针转发对对象实例数据的访问</td>
<td>访问对象实例数据需要经过以此转发，增加访问的开销</td>
</tr>
</tbody></table>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://acexxs.gitee.io/blog-page/2021/10/18/44cac75b5e4e.html" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/blog-page/tags/JVM/" rel="tag">JVM</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/blog-page/tags/Java/" rel="tag">Java</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/blog-page/2021/10/19/2fe2b377cca6.html" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            深入理解JVM（三）垃圾收集基础原理
          
        </div>
      </a>
    
    
      <a href="/blog-page/2021/10/18/903d4bcc7fa1.html" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">深入理解JVM（一）虚拟机内存</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "4Gx0dzptNxW0Nb4xekYQLQF1-gzGzoHsz",
    app_key: "nvoM2TGGO7QpNlr3vAy3DQyg",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "欢迎一起探讨交流~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2021
        <i class="ri-heart-fill heart_icon"></i> ACEXS
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/blog-page/"><img src="/blog-page/images/ayer-side.svg" alt="ACEXS个人博客"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/blog-page/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/blog-page/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/blog-page/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/blog-page/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/blog-page/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/blog-page/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/blog-page/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>表扬一下吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/blog-page/images/alipay.png">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/blog-page/images/wechat.png">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/blog-page/js/jquery-3.6.0.min.js"></script>
 
<script src="/blog-page/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/blog-page/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/blog-page/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/blog-page/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/blog-page/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->
 
<script src="/blog-page/js/dz.js"></script>
 
<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>